﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using SaaS.Core;
using XCore.Web.Jwt;
using XCore.Web.Middleware;

namespace Web.System.Utils
{
    public class SystemAuthorizationMiddleware : AuthorizationMiddleware
    {
        public SystemAuthorizationMiddleware(RequestDelegate next) : base(next)
        {
        }
        public override async Task Invoke(HttpContext context)
        {
            StringValues token = context.Request.Headers.Where(c => c.Key == CoreSetting.Token).FirstOrDefault().Value;
            if (!string.IsNullOrWhiteSpace(token))
            {
                var claim = JWTHelper.GetClaimsPrincipal(token, new JWTOptions
                {
                    Audience = CoreSetting.Audience,
                    Expire = CoreSetting.Expire,
                    Issuer = CoreSetting.Issuer
                });
                context.User = claim;
            }
            await base.Invoke(context);
        }
    }
}
